<template>
  <div class="custom-form-wrap">
    <a-form-model
      ref="form"
      :model="formModel"
      :rules="formRules"
      :label-col="formOptions.labelCol"
      :wrapper-col="formOptions.wrapperCol"
      labelAlign="right"
      :layout="formOptions.layout"
    >
      <template v-for="(formItem, index) in formInstance">
        <a-form-model-item
          :ref="formItem.prop"
          :prop="formItem.prop"
          :label="formItem.label"
          :key="index"
        >
          <RadioGroup
            v-if="formItem.type === 'radio'"
            v-model="formModel[formItem.prop]"
            :value="formModel[formItem.prop]"
            v-bind="formItem"
            v-on="$listeners"
            @emit-update-event="emitUpdateEvent"
            @handle-radio-change="radioChange"
          ></RadioGroup>
          <CustomSelect
            v-else-if="formItem.type === 'select'"
            v-model="formModel[formItem.prop]"
            :value="formModel[formItem.prop]"
            v-bind="formItem"
            @handle-select-change="handleFormCbChange"
            @emit-update-event="emitUpdateEvent"
          ></CustomSelect>
          <!-- 日历 -->
          <CustomDatePicker
            v-else-if="formItem.type === 'dataPick'"
            v-model="formModel[formItem.prop]"
            :value="formModel[formItem.prop]"
            v-bind="formItem"
            @handle-date-change="handleFormCbChange"
          ></CustomDatePicker>
          <CustomRangePicker
            v-else-if="formItem.type === 'dataRangePicker'"
            v-model="formModel[formItem.prop]"
            :value="formModel[formItem.prop]"
            @handle-range-change="handleFormCbChange"
          ></CustomRangePicker>
          <div v-else :class="{ verifyInput: formItem.isAuthCode }">
            <CustomInput
              v-model="formModel[formItem.prop]"
              :value="formModel[formItem.prop]"
              v-bind="formItem"
              @emit-update-event="emitUpdateEvent"
              @pressEnter="enterClick"
            ></CustomInput>
            <img
              v-if="formItem.isAuthCode"
              class="pass-verifyCode"
              alt="验证码"
              title="验证码"
              :src="curCaptchaPath"
              @click="handleCb({ cb: 'refreshAuthCode' })"
            />
          </div>
        </a-form-model-item>
      </template>
    </a-form-model>
    <slot name="other"> </slot>
    <a-form-model-item :wrapper-col="submitButtonOptions.wrapperCol">
      <a-row
        :type="submitButtonOptions.rowType || 'flex'"
        :justify="submitButtonOptions.justify || 'center'"
      >
        <a-col
          v-for="item in submitButtonOptions.buttonList"
          :key="item.title"
          :span="item.col"
          :offset="item.offset"
        >
          <a-button
            :type="item.type"
            :block="item.block"
            :size="item.size"
            @click="handleCb(item)"
            >{{ item.title }}</a-button
          >
        </a-col>
      </a-row>
      <slot name="footer"> </slot>
    </a-form-model-item>
    <slot name="footer-tips"> </slot>
  </div>
</template>

<script>
import CustomInput from '../AntFormItem/CustomInput/index.vue'
import CustomDatePicker from '../AntFormItem/CustomDatePicker/index.vue'
import CustomRangePicker from '../AntFormItem/CustomRangePicker/index.vue'
import RadioGroup from '../AntFormItem/RadioGroup/index.vue'

export default {
  props: {
    curCaptchaPath: String, // 验证码图片
    formRootInstance: Object,
    submitButtonOptions: Object,
    initModel: Object, // 默认值
    formRules: Object,
    tempModel: Object,
    skipValidate: Boolean
  },
  data() {
    return {
      formInstance: {}, // 表单每一个item的List
      formOptions: {}, // 表单其他的配置
      formModel: {} // 表单的value
    }
  },
  components: {
    CustomInput,
    CustomDatePicker,
    CustomRangePicker,
    RadioGroup
  },
  watch: {
    tempModel: {
      // , oVal
      handler(nVal) {
        this.formModel = { ...this.formModel, ...nVal }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.initModelSetting()
  },
  methods: {
    radioChange(value,prop){
      this.formModel[prop] = value
    },
    enterClick() {
      this.handleCb(this.submitButtonOptions.buttonList[0])
    },
    initModelSetting() {
      this.formModel = { ...this.initModel, ...this.tempModel } // 如果有初始值或临时值，则解构出来
      const instance = this.formRootInstance
      const { baseFormConfig, ...otherOptions } = instance
      if (baseFormConfig) {
        // 当存在baseModelItemList(默认都该存在，防止配置出错的问题)
        instance.formConfig = baseFormConfig // 让baseModel作为表单的基础展示
      }
      this.formInstance = instance.formConfig
      this.formOptions = otherOptions
    },
    onSubmit() {
      const validateStatus = this.validatedForm()
      if (validateStatus) {
        this.$emit('submit', {
          form: this.formModel,
          validated: validateStatus
        })
      }
    },
    onRegister() {
      this.$emit('register')
    },
    handleTabsForm(forms) {
      // 处理多tab表单的情况
      if (!this.$isArrayType(forms)) {
        throw new Error('单独处理多tabs表单函数，传入的必须是一个数组形式')
      }
      let resParams = {}
      forms.forEach(form => {
        resParams = { ...resParams, ...form }
      })
      this.$emit('submit', { form: resParams, validated: true })
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.$emit('reseted-form', true)
    },
    clearValidateForm() {
      this.$refs.form.clearValidateForm()
      this.$emit('cleared-form', true)
    },
    emitUpdateEvent(key) {
      this.$nextTick(() => {
        const value = this.formModel[key]
        this.$emit('update-form', { key, value })
      })
    },
    handleCb(item) {
      const { cb } = item
      switch (cb) {
        case 'submit':
          this.onSubmit()
          break
        case 'reset':
          this.resetForm()
          break
        case 'clearValidate':
          this.clearValidateForm()
          break
        case 'register':
          this.onRegister()
          break
        default:
          this.$emit(cb)
          break
      }
    },
    handleFormCbChange(item) {
      const { prop, cb } = item
      if (cb) {
        this.$emit(cb, { value: this.formModel[prop] })
      }
      this.emitUpdateEvent(prop)
    },
    validatedForm() {
      let validateResulte = false
      this.$refs.form.validate((validate, instance) => {
        if (!validate) {
          // 报错
          Object.keys(instance).map(key => {
            const element = instance[key]
            element.forEach(errs => {
              this.$apiStatusHandler(99, errs.message || '表单填写有误')
            })
            validateResulte = false
            return false
          })
        } else {
          validateResulte = true
        }
      })
      return validateResulte
    }
  }
}
</script>
